package com.main.eureka.listener;

import com.netflix.appinfo.InstanceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.eureka.server.event.*;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
@Component
public class ClientEventListener {

    @EventListener
    public void handle(EurekaServerStartedEvent event) {
        System.out.println("START");
        // Eureka server started handling
    }

    @EventListener
    public void handle(EurekaRegistryAvailableEvent event) {
        System.out.println("RegistryAvailable");
        // Eureka registry is available handling
    }
    //‌服务注册（Register）‌：服务提供者（Eureka Client）向服务注册中心（Eureka Server）注册自己的信息，包括服务名、IP地址和端口等
    @EventListener
    public void handle(EurekaInstanceRegisteredEvent event) {
        InstanceInfo instanceInfo = event.getInstanceInfo();
        System.out.println("------------Registered----------");
        System.out.println(instanceInfo);
        log.info("Registered：{}", instanceInfo);
        // Handle instance registered event
    }
    //服务下线（Cancel）‌：当服务提供者关闭时，会向Eureka Server发送消息，将自己从服务列表中删除，防止服务消费者调用到不存在的服务‌
    @EventListener
    public void handle(EurekaInstanceCanceledEvent event) {
        String serverId = event.getServerId();
        System.out.println("------------Canceled----------");
        System.out.println(serverId);
        log.info("Canceled serverId：{}", serverId);
        try {
            callExternalApiUsingHttpURLConnection();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // Handle instance cancel event
    }
    //‌服务续约（Renew）‌：Eureka Client每隔30秒向Eureka Server发送心跳包，告诉Eureka Server该服务仍然可用，没有出现故障‌。
    @EventListener
    public void handle(EurekaInstanceRenewedEvent event) {
        InstanceInfo instanceInfo = event.getInstanceInfo();
        System.out.println("------------Renewed----------");
        System.out.println(instanceInfo);
        log.info("Renewed：{}", instanceInfo);
        // Handle instance renewed event
    }

    public String callExternalApiUsingHttpURLConnection() throws IOException {
        URL url = new URL("http://10.10.14.129:9055/actuator/gateway/refresh");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }

        in.close();
        System.out.println("----------------refresh-------------------"+content.toString());
        return content.toString();
    }

        // ... handle other events as needed
        // 获取服务注册列表（Get Registry）‌：服务消费者获取一份服务注册列表信息，这个列表包含了所有向Eureka Server注册的服务信息，以便进行远程调用‌。
        // ‌集群中数据同步（Replicate）‌：在Eureka集群中，各个节点之间会同步数据，确保所有节点都有最新的服务注册信息‌。
        // 远程调用（Make Remote Call）‌：完成服务的远程调用，服务消费者通过获取的服务注册列表信息调用服务提供者的服务‌
}